import { onMounted, nextTick, ref, Ref ,reactive} from 'vue'
import * as echarts from 'echarts'
import {getOption} from '../components/treeModel'
import MiddleFunction from '../tool/middleFuction'
import cashData from '../utils/treeCashData'
import { useUsersStore } from '../store/index'
import { useRouter } from 'vue-router'
const useEcharts = (id:string,branchName:string)=>{
  interface TreeNode {
    id: number
    label: string
    pid?: number
    children?: TreeNode[]
    name?: string
    size?: number
    x?: number
    y?: number
    level?: number
    collapsed?: boolean
  }
  const router = useRouter() //注册路由
  const route = useRoute() 
  const store = useUsersStore() //数据共享
  const container:Ref = ref(null)
  const myCharts:Ref = ref(null)
  const specifyDoubleClick = reactive({
  isTrue:false,
  clickTime:0
  })
  onMounted(()=>{
    nextTick(()=>{
      container.value = document.getElementById(id)
      myCharts.value = echarts.init(container.value)
      new MiddleFunction().init()
      const newCashData = new MiddleFunction().factory(branchName)
      const option = getOption(newCashData)
      let copyOption = MiddleFunction.deepCopy(option)
      if(branchName === 'head'){
        //首页配置项的处理
        copyOption.series[0].left = "200"
        copyOption.series[0].label.padding = [8,40,8,40]
        copyOption.series[0]["zoom"] = 0.7
        copyOption.series[0]["top"] = "-20%"
      }else{
        //branch页面的修改
        copyOption.series[0]["zoom"] = 0.8
        if(route.query.name && route.query.name.length > 10){
          // 文字长度超过10的,调整左边距
          copyOption.series[0].left = "150"
        }
        copyOption.series[0].label.rich.a.lineHeight = 30
        copyOption.series[0].label.padding = [8,20]
      }
      myCharts.value.setOption(copyOption,true)
      myCharts.value.getZr().off('mousewheel')
      myCharts.value.getZr().on('mousewheel', () => {
        let currentOption = myCharts.value.getOption()
        if (currentOption.series[0]) {
          let zoom = currentOption.series[0].zoom
          changeZoom(currentOption, zoom)
          copyOption && myCharts.value.setOption(currentOption,true)
        }
      })
      myCharts.value.on('click', (e:any) => {
        let maxDepth:number | undefined= new MiddleFunction().getTreeDepth(e.data) 
        //下面如果没有子节点，就不进行点击事件
        if(maxDepth === 0 && branchName !== 'head')return
        const flagFour = MiddleFunction.getThreeNodeList(cashData, 4).includes(e.name) //点击层
        if(MiddleFunction.specifyDouble(e,flagFour,specifyDoubleClick)) return;
        specifyDoubleClick.isTrue = false;
        specifyDoubleClick.clickTime = 0;
        viewAllChildNodes(e)
        if(branchName != 'head'){
          resizeWidth(e)
        }
      })
    })
  })
 // 缩放添加样式
const changeZoom = (currentOption: any, zoom: number) => {
  if(branchName === 'head'){
	currentOption.series[0].label.padding = [8 * zoom, 70 * zoom]
  currentOption.series[0].label.rich.a.lineHeight = 23 * zoom
  }else{
  currentOption.series[0].label.padding = [8 * zoom, 20 * zoom]
  currentOption.series[0].label.rich.a.lineHeight = 30 * zoom
  }
	currentOption.textStyle.fontSize = 14 * zoom
	currentOption.series[0].label.borderRadius = 4 * zoom
	currentOption.series[0].label.shadowBlur = 3 * zoom
	currentOption.series[0].label.rich.b.fontSize = 14 * zoom
	currentOption.series[0].label.rich.b.padding = [0, 5 * zoom, 0, 5 * zoom]
	currentOption.series[0].label.rich.a.fontSize = 20 * zoom
} 
// 点击第三层显示后代所有的子节点
const viewAllChildNodes = (e:any) => {
	const moreData =new MiddleFunction().getSameBranch(cashData, e.name) //查找第三层级所点击后面所有的子节点
  const flagThree = MiddleFunction.getThreeNodeList(cashData, 3).includes(e.name) //是否是第三层级的节点
  const flagFour = MiddleFunction.getThreeNodeList(cashData, 4).includes(e.name) //点击层
  if (flagThree) {
	router.push(`/branch?name=${e.name}`)
  }
  if(flagFour && branchName != "head"){
		store.singleBranch = store.singleBranch.map((item: TreeNode) => {
			if (item.name && moreData.includes(item.name)) {
				item.collapsed = !item.collapsed
			}else if(!MiddleFunction.getThreeNodeList(cashData, 3).includes(item.name)){
        item.collapsed = true
      }
			return item
		})
		let currentOption = myCharts.value.getOption()
		currentOption.series[0].left = '10%'
		currentOption.series[0].data = new MiddleFunction().factory(branchName)
		myCharts.value.setOption(currentOption)
		myCharts.value.resize()
  }

}
// 随着层级的增加，宽度变化
const resizeWidth = (e:any) => {
  const flagFour = MiddleFunction.getThreeNodeList(cashData, 4).includes(e.name) //获取下一级的是否点击的是第二层数据
  const newCashData = new MiddleFunction().factory(branchName)
  const option = getOption(newCashData)
  let currentOption = MiddleFunction.deepCopy(option)
  if(!flagFour) return //只给branch第二层数据绑定点击事件
  let maxDepth:number= new MiddleFunction().getTreeDepth(e.data) ?? 0
	if (e.componentType === 'series' && maxDepth !== 0) {
		if (!e.value) {
			var dataIndex = e.dataIndex
			var isExpand = false
			const nodes = myCharts.value._chartsViews[0]._data.tree._nodes
			for (var i = 0; i < nodes.length; i++) {
				if (nodes[i].dataIndex === dataIndex) {
					if (nodes[i].children.length == 0) {
						return false
					} else {
						isExpand = nodes[i].isExpand
						maxDepth = isExpand ? maxDepth : 2
						break
					}
				}
			}
			for (var i = 0; i < nodes.length; i++) {
				if (nodes[i].depth == 2 && nodes[i].isExpand) {
					for (var j = i + 1; nodes[j].isExpand; j++) {
						maxDepth = Math.max(nodes[j].depth, maxDepth)
           if(j >= nodes.length -1) break
					}
				}
			}
			if (maxDepth > 2) {
				//设置的超过3个层级，改变宽度
				container.value.style.width = 100 + (maxDepth - 3) * 10 + '%'
        if(e.name === "控告申诉检察部门受理1"){
          currentOption.series[0].left = '10%'
        }else{
          currentOption.series[0].left = 1000 / (100 + (maxDepth - 3) * 20) + '%'
        }
        myCharts.value.setOption(currentOption,true)
				myCharts.value.resize()
			} else {
				container.value.style.width = 50 + '%'
        currentOption.series[0].left = 1000 / 50 + '%'
        currentOption.series[0]["zoom"] = 0.8
        myCharts.value.setOption(currentOption,true)
				myCharts.value.resize()
			}
      //去除重复背景
      const HtmlDom = document.getElementById("branch")
      const branchWidth:any = HtmlDom !== null ? HtmlDom!.style!.width : null;
      if(branchWidth && branchWidth.slice(0,-1)*1 > 100){
        // HtmlDom!.style!.background = "url('/image/banner.png') center no-repeat"
        HtmlDom!.style!.backgroundSize = "cover"
      }else{
        HtmlDom!.style!.background = 'transparent'
      }
		}
		// 高度设置
		// const eleArr = Array.from(
		// 	new Set(myCharts.value._chartsViews[0]._data._graphicEls)
		// )
		// const itemHeight = 25
		// const currentHeight = itemHeight * (eleArr.length - 1) || itemHeight
		// const newHeight = Math.max(currentHeight, itemHeight)
		// container.value.style.height = newHeight
		// myCharts.value.resize({
		// 	height: newHeight,
		// })
	}
}
}
export default useEcharts